<!DOCTYPE html>
<html>
<head>
	
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>加载中...</title>
	<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> 
	
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

	<!-- ZUI 标准版压缩后的 CSS 文件 -->
	<link rel="stylesheet" href="/css/zui.min.css">
	<link rel="stylesheet" href="/css/mzui.min.css">
	<!-- custom css -->
	<link rel="stylesheet" type="text/css" href="/css/index.css">	

</head>
<body class="player-body">

<input type="hidden" id="code" value="${code!}" />
<input type="hidden" id="from" value="${from!}" />
<input type="hidden" id="vodId" value="${vodId!}" />
<input type="hidden" id="epIdx" value="${epIdx!}" />
<input type="hidden" id="time" value="${time!}" />

<div class="heading">
	<div class="title">
		<strong id="play-title">加载中...</strong>	
	</div>
	<nav class="nav">
		<a data-display data-backdrop="true" data-target="#play-list-box" data-placement="bottom"><i class="icon-10x icon-th-list"></i></a>
	</nav>	
</div>
<div class="section">
	<!-- 指定播放器容器 -->
	<div class="artplayer-app" style="aspect-ratio: 16/9;"></div>
</div>

<!-- 播放列表弹框 -->
<div id="play-list-box" class="affix dock-bottom modal hidden" style="max-height: 20rem;">
  <div class="heading">
    <div class="title"><strong>播放列表</strong></div>
    <nav class="nav"><a data-dismiss="display"><i class="icon-remove muted"></i></a></nav>
  </div>
  <div class="content article box">
    <div class="list" id="ep-list">
		<!--
  		<a class="item">
			<div class="title ep-active">第一集</div>
    		<img src="/img/playing.gif" width="20px" height="10px"/>	  
		</a>
		-->
	</div>
  </div>
</div>


<!-- 播放列表模板 -->
<script id="play-list-item" type="text/html">
{{each epList ep idx}}
<a class="item" data-url="{{ep.url}}" data-idx="{{idx}}" data-name="{{ep.html}}">
	<div class="title {{if ep.default}}ep-active{{/if}}">
		{{ep.html}}
		{{if ep.default}}
		<div class="pull-right" >
			<img src="/img/playing.gif" width="10px" height="5px" style="margin-top: auto;margin-bottom: auto;"/>
			<small style="color: cornflowerblue;margin-top: auto;margin-bottom: auto;">播放中</small>
		</div>
		{{/if}}
	</div> 
</a>
{{/each}}	
</script>


<!-- ZUI Javascript 依赖 jQuery -->
<script type="text/javascript" src="/js/jquery.js"></script>
<!-- ZUI 标准版压缩后的 JavaScript 文件 -->
<script type="text/javascript" src="/js/zui.min.js"></script>
<script type="text/javascript" src="/js/mzui.min.js"></script>
<!-- 引入基础脚本 mui-player.min.js -->
<script type="text/javascript" src="/js/hls.min.js"></script>
<script type="text/javascript" src="/js/artplayer.js"></script>
<!-- Art-Template.js -->
<script type="text/javascript" src="/js/template-web.min.js"></script>

<!-- 播放历史 -->
<script type="text/javascript" src="/js/free-gt/history.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/artplayer-plugin-danmuku/dist/artplayer-plugin-danmuku.js"></script>

<script>
	
/** 全局变量 */
var Global_Code = '';
var Global_Vid = 0;

var Global_From = '';
var Global_Name = '';
var Global_EP_Name = '';
var Global_PIC = '';
var Global_Play_List = [];
var Global_Play_Index = 0;
var Global_Auto_Loop = true;	

// https://api.bilibili.com/x/v1/dm/list.so?oid=1423211120

Artplayer.CONTEXTMENU = false;
// 自动重连次数
RECONNECT_TIME_MAX = 1;
// 通知显示事件（毫秒）
Artplayer.NOTICE_TIME = 5000;
/** 播放器初始化 */
const art = new Artplayer({
    container: '.artplayer-app',
    //url: '',
    theme: '#ffad00', // 主题颜色
    type: 'm3u8',
    customType: {m3u8: playM3u8,},
    // fullscreenWeb: true, // 网页全屏
    pip: true, // 画中画
    fullscreen: true, // 全屏
    hotkey: true, // 键盘控制播放
    // autoSize: true, // 播放器自动填充容器大小
    autoplay: true, // 是否自动播放      
    playsInline: true, // 移动端是否启用 playsInline  模式
    lock: true, // 移动端是否显示锁定按钮
    fastForward: true, // 移动端添加长按快进功能
    autoOrientation: true, // 是否在移动端的网页全屏时，根据视频尺寸和视口尺寸，旋转播放器
    /**
    controls: [
        {
            name: 'btn-list',
            position: 'right',
            html: '<i class="icon icon-th-list" style="font-size:20px"></i>',
            selector: [],
            onSelect: function (item, $dom) {
				// 全局播放进度
				Global_Play_Index = item.idx;
				Global_Play_List.forEach(function(value,index){
					Global_Play_List[index].default = false;
				});
				Global_Play_List[Global_Play_Index].default = true;
				
	            // title
	  			$('title').html(Global_Name + '-' + item.html)
	  			$('#play-title').html(Global_Name + '-' + item.html)
	  			art.switch = item.url;
  			
                return '<i class="icon icon-th-list" style="font-size:20px"></i>';
            },
        },
    ],
    */
    setting: true, // 设置
    // flip: true, // 画面翻转
    playbackRate: true, // 播放速度
    aspectRatio: true, // 画面比例
    // subtitleOffset: true, // 字幕时间轴偏移
    settings: [
        {
            html: '自动连播',
            tooltip: '默认',
            icon: '<i class="icon icon-forward" style="font-size:20px"></i>',
            switch: true,
            onSwitch: function (item, $dom, event) {
                
                const nextState = !item.switch;                
                item.tooltip = nextState ? '开' : '关';
                
                Global_Auto_Loop = nextState;
                
                console.info('自动连播: ' + Global_Auto_Loop);
                
                return nextState;
            },
        },
    ],
    /**
    plugins: [
        artplayerPluginDanmuku({
            // 弹幕 XML 文件，和 Bilibili 网站的弹幕格式一致
            danmuku: 'https://api.bilibili.com/x/v1/dm/list.so?oid=1423211120',
        }),
    ],
    */
});

/** Support HLS **/
function playM3u8(video, url, art) {
    if (Hls.isSupported()) {
        if (art.hls) art.hls.destroy();
        const hls = new Hls({
			autoStartLoad: true,
            debug: false,
            manifestLoadingTimeOut : 60000,
            /*manifestLoadingMaxRetry : 9,*/
            manifestLoadingRetryDelay : 500,
            levelLoadingTimeOut : 60000,
            /*levelLoadingMaxRetry : 9,*/
            levelLoadingRetryDelay : 500,
            fragLoadingTimeOut : 60000,
            /*fragLoadingMaxRetry : 6,*/
            fragLoadingRetryDelay : 250,
            startFragPrefetch : true
		});
        hls.loadSource(url);
        hls.attachMedia(video);
        art.hls = hls;
        art.on('destroy', () => hls.destroy());
    } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
        video.src = url;
    } else {
        art.notice.show = 'Unsupported playback format: m3u8';
    }
}

/** 播放器首次可以播放时事件 */
art.on('ready', () => {
	console.info('ArtPlayer First Already !');
    // art.play();
    var time = $('#time').val();
    if(time != null && time > 0){
		 art.currentTime = time;
		 art.notice.show = '自动跳转至上次播放位置 : ' + formatSeconds2(time);
		 $('#time').val(0);
	}
});

/** 播放器可以播放事件 */
art.once('video:canplay', () => {
    console.info('video:canplay');
    //art.play();
});

/** 播放器自动设置大小事件 */
art.on('autoSize', () => {
    console.info('Video:AutoSize');
    //art.fullscreenWeb = true;
});


/** 时间轴变化事件 */
var last_Play_Record = 0;
art.on('video:timeupdate', (state) => {
	
	// 自动播放提示
	if(Global_Auto_Loop && art.duration > 0 && art.duration - art.currentTime <= 10){
		art.notice.show = '即将播放' + (Global_Play_List[Global_Play_Index + 1].html);
	}
	
	// 重置为零
	if(last_Play_Record > art.currentTime){
		last_Play_Record = 0;
	}
	
	// 播放历史
	if(art.currentTime - last_Play_Record > 5){
		his_save(Global_Code, Global_Vid, Global_Play_Index, '[' + Global_From + ']' + Global_Name + '-' + Global_EP_Name, Global_PIC, art.currentTime);
		last_Play_Record = art.currentTime;
	}   
});


/** 播放结束事件 */
art.on('video:ended', () => {
	
	var playListSize = Global_Play_List.length;
	
	if(Global_Play_Index >= playListSize - 1){
		art.notice.show = '播放结束';
		return;
	}
	
	Global_Play_List[Global_Play_Index].default = false;
	Global_Play_Index += 1;
	
	Global_Play_List[Global_Play_Index].default = true;
	
	if(Global_Auto_Loop){
		art.switch = Global_Play_List[Global_Play_Index].url;
		
		// 更新"播放列表"
	  	updateEpList(Global_Play_List)
	    
	    // 更新 Title
	    Global_EP_Name = Global_Play_List[Global_Play_Index].html;
	    $('title').html(Global_Name + '-' + Global_EP_Name)
	    $('#play-title').html(Global_Name + '-' + Global_EP_Name)
	}	
	
});


/** 网页加载完成 */
$(function(){
	
	var code = $('#code').val();
	var from = $('#from').val();
    var vodId = parseInt($('#vodId').val());
    var epIdx = parseInt($('#epIdx').val());
    
    Global_Code = code;
    Global_From = from;
    Global_Vid = vodId;
    
    // 请求播放连接
    $.ajax({
		type: "GET",
        url: "/video/play/load?code=" + code + '&vodId=' + vodId,
        dataType: "json",
        success: function(data){
			
			var playList = data.playList;
			
			if(epIdx < playList.length){
				Global_Play_Index = epIdx;
			}
			
			var currentPlayName = playList[Global_Play_Index].html;
          	var currentPlayUrl = playList[Global_Play_Index].url;
 	
          	playList[Global_Play_Index].default = true;
          	
          	Global_Play_List = playList;         	
          	Global_Name = data.name;         	
          	Global_EP_Name = currentPlayName;
          	Global_PIC = data.pic
          	
          	// title
          	$('title').html(Global_Name + '-' + currentPlayName);
          	$('#play-title').html(Global_Name + '-' + currentPlayName)
          	
          	
          	// 播放
          	art.url = currentPlayUrl;
          	
          	// 更新移动端播放列表
          	updateEpList(playList)
          	
          	// 播放历史
          	his_save(Global_Code, Global_Vid, Global_Play_Index, '[' + Global_From + ']' + Global_Name + '-' + Global_EP_Name, Global_PIC, 0);   	
          	
        },
        error: function(err){
			 art.notice.show = '系统发生错误，请稍后再访问！';
		}
	});
});

/** 更新播放列表 */
function artUpdateControls(playList){
	// 更新"播放列表"
  	art.controls.update({
		name: 'btn-list',
        position: 'right',
        html: '<i class="icon icon-th-list" style="font-size:20px"></i>',
        selector: playList,
        onSelect: function (item, $dom) {
			
			// 全局播放进度
			Global_Play_Index = item.idx;
			Global_Play_List.forEach(function(value,index){
				Global_Play_List[index].default = false;
			});
			Global_Play_List[Global_Play_Index].default = true;	
			Global_EP_Name = item.html;
			
            // title
  			$('title').html(Global_Name + '-' + item.html);
  			$('#play-title').html(Global_Name + '-' + item.html);
  			art.switch = item.url;
            
            return '<i class="icon icon-th-list" style="font-size:20px"></i>';
        },
    });
}

/**更新移动端播放列表**/
function updateEpList(epList){
	let result = template('play-list-item',{'epList' : epList});  //===注意点:  模板上得rows要跟template上得rows对应
    $('#ep-list').html(result) //===直接赋值就可以实现了
}

/**a 标签点击事件*/
$('#ep-list').on('click', 'a', function(){
	var url = $(this).attr('data-url');
	var idx = $(this).attr('data-idx');
	var epName = $(this).attr('data-name');
	
	// 全局播放进度
	Global_Play_Index = parseInt(idx);
	Global_Play_List.forEach(function(value,index){
		Global_Play_List[index].default = false;
	});
	Global_Play_List[Global_Play_Index].default = true;	
	Global_EP_Name = epName;
	
	// 更新播放列表
	updateEpList(Global_Play_List);
	
    // title
	$('title').html(Global_Name + '-' + Global_EP_Name);
	$('#play-title').html(Global_Name + '-' + Global_EP_Name);
	art.switch = url;
});

</script>
</body>
</html>